package com.jsz.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.jsz.dao.OrderSettingDao;
import com.jsz.pojo.OrderSetting;
import com.jsz.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceimpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    //保存上传的文件
    @Override
    public void add(List<OrderSetting> data) {
        //判断
        if (data != null && data.size() > 0) {
            //进行数据遍历
            for (OrderSetting orderSetting : data) {
                //判断当前日期是否已经进行了预约设置
                long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if (countByOrderDate > 0) {
                    //已经进行了预约数据,那么就修改已经保存的数据
                    orderSettingDao.updateNumberByOrderDate(orderSetting);
                } else {
                    //没有进行预约设置,那么就保存数据到数据库
                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }

    //根据月份查询当前预约数
    @Override
    public List<Map> getOrderSettingByMonth(String date) {
        //此时的data是 yyyy-MM 格式
        //传入的data数据进行字符串的拼接
        String begin = date + "-1";
        String end = date + "-31";
        //封装进map集合中
        Map<String, String> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        //调用dao层,操作数据
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(map);

        //定义一个map集合用来封装数据
        List<Map> result = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (OrderSetting orderSetting : list) {
                Map<String, Object> m = new HashMap<>();
                //这里的Map中的kay值取名一定要和页面中要求的名字相同,不然数据传过去不能正常封装展示
                //getDate()获取日期数字,也就是几号 (2020-3-17, 这里获取到的数据就是后面这个17)
                m.put("date", orderSetting.getOrderDate().getDate());
                m.put("number", orderSetting.getNumber());
                m.put("reservations", orderSetting.getReservations());
                result.add(m);
            }
        }
        return result;
    }

    @Override
    public void updateNumberByOrderDate(OrderSetting orderSetting) {
        //根据日期查询是否已经进行了预约设置
        Date orderDate = orderSetting.getOrderDate();
        long countByOrderDate = orderSettingDao.findCountByOrderDate(orderDate);
        //判断
        if (countByOrderDate > 0) {
            //当前日期已经进行了预约设置,执行更新操作
            orderSettingDao.updateNumberByOrderDate(orderSetting);
        } else {
            //当前日期没有进行预约设置,执行插入操作
            orderSettingDao.add(orderSetting);
        }
    }
}
